<template>
  <base-layout>
    <div class="page-container">
      <a-card class="form-card" :bordered="false">
        <template #title>
          <div class="card-title">
            <a-button @click="handleBack">
              <template #icon><arrow-left-outlined /></template>
              返回
            </a-button>
            <h2>新增项目</h2>
          </div>
        </template>

        <a-form
          :model="formState"
          :rules="rules"
          ref="formRef"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="项目名称" name="name">
            <a-input v-model:value="formState.name" placeholder="请输入项目名称" />
          </a-form-item>

          <a-form-item label="所属课程" name="course">
            <a-select
              v-model:value="formState.course"
              placeholder="请选择所属课程"
              :options="courseOptions"
            />
          </a-form-item>

          <a-form-item label="项目类型" name="type">
            <a-radio-group v-model:value="formState.type" button-style="solid">
              <a-radio-button value="course">课程项目</a-radio-button>
              <a-radio-button value="comprehensive">综合项目</a-radio-button>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="项目描述" name="description">
            <a-textarea
              v-model:value="formState.description"
              placeholder="请输入项目描述"
              :rows="4"
              :maxlength="500"
              show-count
            />
          </a-form-item>

          <a-form-item label="项目分值" name="points">
            <a-input v-model:value="formState.points" placeholder="请输入项目分值" />
          </a-form-item>

          <a-form-item label="开始时间" name="startTime">
            <a-date-picker
              v-model:value="formState.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="结束时间" name="endTime">
            <a-date-picker
              v-model:value="formState.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择结束时间"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item label="项目文档" name="document">
            <a-upload
              v-model:file-list="fileList"
              :max-count="1"
              :before-upload="beforeUpload"
            >
              <a-button>
                <template #icon><upload-outlined /></template>
                上传文档
              </a-button>
              <template #itemRender="{ file }">
                <a-card size="small" class="upload-card">
                  <template #actions>
                    <download-outlined key="download" @click="handleDownload(file)" />
                    <delete-outlined key="delete" @click="handleRemove(file)" />
                  </template>
                  <a-card-meta>
                    <template #title>{{ file.name }}</template>
                    <template #description>
                      <div class="file-info">
                        <span>{{ formatFileSize(file.size) }}</span>
                        <span>{{ file.status === 'done' ? '上传成功' : '上传中...' }}</span>
                      </div>
                    </template>
                  </a-card-meta>
                </a-card>
              </template>
            </a-upload>
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
            <a-space>
              <a-button type="primary" @click="handleSubmit">提交</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </base-layout>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import {
  ArrowLeftOutlined,
  UploadOutlined,
  DownloadOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import {createProjects} from "@/api/projects.js";

export default {
  name: 'ProjectCreate',
  components: {
    BaseLayout,
    ArrowLeftOutlined,
    UploadOutlined,
    DownloadOutlined,
    DeleteOutlined
  },
  setup() {
    const router = useRouter()
    const formRef = ref()
    const fileList = ref([])

    const formState = reactive({
      name: '',
      course: undefined,
      type: 'course',
      description: '',
      points: 100,
      startTime: null,
      endTime: null,
      document: undefined,
      documentFile: null
    })

    const courseOptions = [
      { value: 'java', label: '面向对象程序设计（Java）' },
      { value: 'web', label: 'Web应用开发' },
      { value: 'database', label: '数据库原理' }
    ]

    const rules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 3, max: 50, message: '项目名称长度应在 3-50 个字符之间', trigger: 'blur' }
      ],
      course: [
        { required: true, message: '请选择所属课程', trigger: 'change' }
      ],
      type: [
        { required: true, message: '请选择项目类型', trigger: 'change' }
      ],
      description: [
        { required: true, message: '请输入项目描述', trigger: 'blur' },
        { min: 10, max: 500, message: '项目描述长度应在 10-500 个字符之间', trigger: 'blur' }
      ],
      points: [
        { required: true, message: '请输入项目分值', trigger: 'blur' },
        { type: 'number', min: 0, max: 1000, message: '分值应在 0-1000 之间', trigger: 'blur' }
      ],
      startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change', type: 'object' }
      ],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change', type: 'object' }
      ]
    }

    const handleBack = () => {
      router.back()
    }

    const handleSubmit = async () => {
      try {
        const isValid = await formRef.value.validate()
        if (!isValid) {
          return
        }
        
        message.loading('提交中...', 0)
        
        await createProjects(formState)
        
        message.destroy()
        message.success('创建成功')
        router.push('/project-manage')
      } catch (error) {
        message.destroy()
        message.error('创建失败：' + (error.message || '未知错误'))
        console.error('提交错误:', error)
      }
    }

    const handleReset = () => {
      formRef.value.resetFields()
      fileList.value = []
    }

    const beforeUpload = (file) => {
      const isDoc = file.type === 'application/pdf' || 
                   file.type === 'application/msword' || 
                   file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      if (!isDoc) {
        message.error('只能上传 PDF 或 Word 文档！')
        return false
      }
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        message.error('文件大小不能超过 10MB！')
        return false
      }
      
      // Save the file to formState for later submission
      formState.documentFile = file
      
      // Add to fileList for display
      fileList.value = [file]
      
      return false // 阻止自动上传
    }

    const handleDownload = (file) => {
      message.info(`下载文件: ${file.name}`)
    }

    const handleRemove = (file) => {
      fileList.value = fileList.value.filter(item => item.uid !== file.uid)
      formState.documentFile = null
    }

    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else {
        return (size / 1024 / 1024).toFixed(2) + ' MB'
      }
    }

    return {
      formRef,
      formState,
      fileList,
      courseOptions,
      rules,
      handleBack,
      handleSubmit,
      handleReset,
      beforeUpload,
      handleDownload,
      handleRemove,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.form-card {
  border-radius: 8px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-title h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-upload-wrapper) {
  width: 100%;
}

.upload-card {
  margin-top: 8px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-form-item-label) {
  text-align: right;
  padding-right: 16px;
}

:deep(.ant-radio-group) {
  display: flex;
}

:deep(.ant-radio-button-wrapper) {
  min-width: 120px;
  text-align: center;
}
</style> 